package dom;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;

public class Test {
    public static void main(String[] args)throws Exception {
        //parse("my.xml");
        create();
    }

    public static void parse(String name) throws Exception {
        //创建解析器
        SAXReader r=new SAXReader();
        Document doc=r.read(Test.class.getResourceAsStream(name));
        //System.out.println(doc.asXML());

        //获取文档的根节点
        Element root=doc.getRootElement();
        //获取节点下所有子节点
        List<Element>childs= root.elements();
        childs=root.elements("stu");
        Element first=childs.get(0);
        System.out.println("标签中属性为name的值为："+first.attributeValue("name")+",标签名为："+first.getName());
        System.out.println("标签中间的内容："+first.getTextTrim());
    }

    static void create() throws Exception {
        Document doc= DocumentHelper.createDocument();
        //添加根节点<books></books>
        Element books=doc.addElement("books");
        //添加子元素
        Element b1=books.addElement("book");
        Element title1=b1.addElement("title");
        Element author1=b1.addElement("author");

        Element b2=books.addElement("book");
        Element title2=b2.addElement("title");
        Element author2=b2.addElement("author");

        //为元素添加内容
        title1.setText("三国演义");
        author1.setText("罗贯中");
        b1.addAttribute("id","001");
        title2.setText("红楼梦");
        author2.setText("曹雪芹");

        OutputFormat f=OutputFormat.createPrettyPrint();
        XMLWriter writer=new XMLWriter(new FileOutputStream("books.xml"),f);
        writer.write(doc);
        writer.close();


    }
}
